﻿using MiniFox.Components;
using System.Text;
using TemplateEngine.Configurations;
using TemplateEngine.Models;

namespace TemplateEngine.Providers
{
    /// <summary>
    /// 
    /// </summary>
    [AutoRegister, SpareComponent(typeof(DefaultTemplateProvider))]
    public interface ITemplateDataProvider
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        TemplateDo GetTemplate(string name);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        Task<TemplateDo> GetTemplateAsync(string name);
    }

    internal class DefaultTemplateProvider : ITemplateDataProvider
    {
        [AutoConfigure]
        public TemplateCollection Templates { get; set; }

        public TemplateDo GetTemplate(string name)
        {
            var template = this.Templates[name];
            using (StreamReader reader = new StreamReader(template.Path, Encoding.UTF8))
            {
                string content = reader.ReadToEnd();
                return new TemplateDo
                {
                    Name = name,
                    DisplayName = template.Title,
                    Content = content
                };
            }
        }
        public async Task<TemplateDo> GetTemplateAsync(string name)
        {
            var template = this.Templates[name];
            using (StreamReader reader = new StreamReader(template.Path, Encoding.UTF8))
            {
                string content = await reader.ReadToEndAsync();
                return new TemplateDo
                {
                    Name = name,
                    DisplayName = template.Title,
                    Content = content
                };
            }
        }
    }
}
